package garage

import (
	"beesoft.ink/application/garage/app/g"
	"beesoft.ink/application/garage/app/model/garage"
	"beesoft.ink/application/garage/app/service"
	"github.com/labstack/echo/v4"
	"gorm.io/gorm/clause"
)

var WarehouseEntry = warehouseEntry{}

type warehouseEntry struct{}

func (r warehouseEntry) List(ctx echo.Context, req *garage.WarehouseEntryListReq) []garage.WarehouseEntry {
	var items []garage.WarehouseEntry

	user, err := service.Auth.ParseAuth(ctx)
	if err != nil {
		ctx.Logger().Error("WarehouseEntryList ParseAuth error: %+v", err)
	}
	if user == nil || user.Id == 0 {
		ctx.Logger().Error("WarehouseEntryList ParseAuth nil, user: %+v", user)
		return items
	}

	g.DB().
		Where("created_by", user.Id).
		Order(clause.OrderByColumn{
			Column: clause.Column{
				Name: req.Order,
			},
			Desc: req.OrderDirection,
		}).
		Offset((req.Page - 1) * req.PageSize).
		Limit(req.PageSize).
		Find(&items)

	return items
}
func (r warehouseEntry) Show(ctx echo.Context) (*garage.WarehouseEntry, error) {
	var item *garage.WarehouseEntry

	id := ctx.Param("id")

	user, err := service.Auth.ParseAuth(ctx)
	if err != nil {
		ctx.Logger().Error("WarehouseEntryList ParseAuth error: %+v", err)
		return item, err
	}

	if err := g.DB().
		Where("created_by", user.Id).
		First(&item, id).Error; err != nil {
		return nil, err
	}

	return item, nil
}
func (r warehouseEntry) Store(ctx echo.Context) (uint, error) {
	item := new(garage.WarehouseEntryReq)

	if err := ctx.Bind(item); err != nil {
		return 0, err
	}

	user, err := service.Auth.ParseAuth(ctx)
	if err != nil {
		ctx.Logger().Error("WarehouseEntryList ParseAuth error: %+v", err)
	}

	// Vehicle
	item.Vehicle.CreatedBy = user.Id
	g.DB().Create(&item.Vehicle)

	// WarehouseEntry
	item.VehicleId = item.Vehicle.ID
	item.WarehouseEntry.CreatedBy = user.Id
	g.DB().Create(&item.WarehouseEntry)

	return item.WarehouseEntry.ID, nil
}
func (r warehouseEntry) Update(ctx echo.Context) error {
	id := ctx.Param("id")

	var item *garage.WarehouseEntry
	if err := g.DB().First(&item, id).Error; err != nil {
		return err
	}

	if err := ctx.Bind(&item); err != nil {
		return err
	}

	g.DB().Save(&item)

	return nil
}
func (r warehouseEntry) Destroy(ctx echo.Context, id uint) error {
	var item *garage.WarehouseEntry
	if err := g.DB().First(&item, id).Error; err != nil {
		return err
	}

	g.DB().Delete(&item)

	return nil
}
